<?php

namespace Frieza\Modules\Material\Controllers;

use App\Http\Controllers\Controller;
use Doraemon\model\Blank;
use Doraemon\model\IdeaBook;
use Doraemon\model\Ideabookcollect;
use Doraemon\service\Member;
use Doraemon\service\Article;
use Doraemon\service\Material\MaterialDownload;
use Doraemon\service\Photos;
use Doraemon\model\Photos as dbPhotos;
use Doraemon\service\Videos\Videos;
use Doraemon\tools\Checker;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use GuzzleHttp\Psr7\Uri;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Tab;
use Doraemon\tools\ImgUrl;
use Illuminate\Support\MessageBag;
use Illuminate\Support\Facades\Auth;
use Doraemon\service\DingTalkAlert;

class MaterialDownloadController extends Controller
{
    private $objId;
    private $sw;
    private $searchDate;
    private $uniId;
    private $imgSize;

    const MAX_OBJ_ID_LENGTH = 10;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }


    public function index(Request $request, Content $content)
    {
        $request = $request->all();
        $materialType = $request['materialType'] ?? MaterialDownload::MATERIAL_TYPE_DEFAULT;
        $allMaterialInfo = MaterialDownload::getAllMaterialInfo();
        $allImgSizeList = MaterialDownload::getAllImgSizeList();
        $allMaterialImgSizeList = [];
        foreach ($allMaterialInfo as $key => $value) {
            foreach ($allImgSizeList as $imgSize => $imgSizeConfig) {
                if (!empty($imgSizeConfig['scene']) &&
                    (in_array(MaterialDownload::ALL_SCENE, $imgSizeConfig['scene'])
                        || in_array($key, $imgSizeConfig['scene']))) {
                    $allMaterialImgSizeList[$key][$imgSize] = $imgSizeConfig;
                }
            }
        }
        $tab = new Tab();
        foreach ($allMaterialInfo as $key => $materialInfo) {
            $tab->add($materialInfo['title'], $this->indexAction($key, $materialInfo, $allMaterialImgSizeList, $request), $key == $materialType ? true : false, $key);
        }
        return $content
            ->header('素材管理')
            ->breadcrumb(
                [
                    'text' => '素材下载',
                    'url' => '/material/download/index'
                ],
            )
            ->body($tab);
    }

    private function indexAction($materialType, $materialInfo, $allMaterialImgSizeList, $requestParams)
    {
        $objId = $requestParams['obj_id'] ?? '';
        $sw = $requestParams['sw'] ?? '';
        $sw = $sw && $sw[0] ? 1 : 0;
        $searchDate = $requestParams['search_date'] ?? date('Y-m-d');
        $imgSize = $requestParams['img_size'] ?? ImgUrl::IMAGE_SIZE_ORIGINAL;
        $form = new Form();
        $form->hidden('materialType')->default($materialType);
        if ($materialInfo[MaterialDownload::IS_SHOW_OBJ_ID]) {
            $toast = '请输入' . $materialInfo['objName'] . 'id';
            if ($materialInfo[MaterialDownload::IS_BATCH]) {
                $toast .= "，多个id用英文逗号分隔，最多可添加".self::MAX_OBJ_ID_LENGTH."个";
            }
            $form->textarea('obj_id', $materialInfo['objName'] . 'id')
                ->default($objId)
            ->placeholder($toast);
        }
        if ($materialInfo[MaterialDownload::IS_SHOW_SW]) {
            $form->checkbox('sw', '昵称水印')->options(['1' => '显示'])->default([$sw]);
        }
        if ($materialInfo[MaterialDownload::IS_SHOW_DATE]) {
            $form->date('search_date', '日期')
                ->default($searchDate);
        }
        if ($materialInfo[MaterialDownload::IS_SHOW_IMG_SIZE]) {
            $options = [];
            foreach ($allMaterialImgSizeList[$materialType] as $_imgSize => $imgSizeConfig) {
                $options[$_imgSize] = $imgSizeConfig['title'];
            }
            $form->radio('img_size', '图片规格')->options($options)->default($imgSize);
        }
        $form->action('/admin/material/download/save');

        return $form;
    }

    public function save(Request $request, Content $content)
    {
        $request = $request->all();
        $materialType = $request['materialType'] ?? '';
        $objId = $request['obj_id'] ?? '';
        $sw = $request['sw'] ?? '';
        $sw = $sw && $sw[0] ? 1 : 0;
        $searchDate = $request['search_date'] ?? '';
        $imgSize = $request['img_size'] ?? '';
        $objId = trim($objId, ',');
        //获取登录用户信息
        $loginUserInfo = Auth::guard('admin')->user()->toArray();
        $email = $loginUserInfo['email'] ?? '';

        $url = "/admin/material/download/index";
        $urlMaker = new Uri($url);
        $urlMaker = Uri::withQueryValues($urlMaker, [
            'materialType' => $materialType,
            'sw' => $sw,
            'obj_id' => $objId,
            'search_date' => $searchDate,
            'img_size' => $imgSize,
        ]);
        if (empty($email)) {
            return redirect(url(strval($urlMaker)))->with(['error' => new MessageBag([
                'title' => '请先补充您的邮箱信息'
            ])]);
        }
        if (empty($materialType)) {
            return redirect(url(strval($urlMaker)))->with(['error' => new MessageBag([
                'title' => '操作类型不存在，操作失败'
            ])]);
        }
        if (empty($objId) && empty($sw) && empty($searchDate)) {
            return redirect(url(strval($urlMaker)))->with(['error' => new MessageBag([
                'title' => '筛选项不能全为空，请至少选择一项'
            ])]);
        }
        $objId = explode(',', trim($objId));
        if (count($objId) > self::MAX_OBJ_ID_LENGTH) {
            return redirect(url(strval($urlMaker)))->with(['error' => new MessageBag([
                'title' => '一次最多只能处理'.self::MAX_OBJ_ID_LENGTH.'条数据'
            ])]);
        }
        // 素材下载时发送通知
        $name = Admin::user()->find(Admin::user()->id)->name;
        $type = MaterialDownload::MATERIAL_TYPE_MAP[$materialType];
        $materialObjId = implode(',', $objId);
        $msg = "$name 执行素材下载任务 \n 素材类型为: 「{$type}」\n 素材id为:「{$materialObjId}」";
        DingTalkAlert::sendTextMsg(DingTalkAlert::MATERIAL_DOWNLOAD, $msg);

        $this->objId = $objId;
        $this->sw = $sw;
        $this->searchDate = $searchDate;
        $this->imgSize = $imgSize;
        $this->uniId = $this->objId ? md5(implode(',', $this->objId)) : $this->searchDate;
        $result = [];
        switch ($materialType) {
            case MaterialDownload::MATERIAL_TYPE_PHOTO:
                $result = $this->download_photo();
                break;
            case MaterialDownload::MATERIAL_TYPE_ARTICLE:
                $result = $this->download_article();
                break;
            case MaterialDownload::MATERIAL_TYPE_USER_AVATAR:
                $result = $this->download_user();
                break;
            case MaterialDownload::MATERIAL_TYPE_IDEABOOK:
                $result = $this->download_ideabook();
                break;
            case MaterialDownload::MATERIAL_TYPE_BLANK:
                $result = $this->download_blank();
                break;
            case MaterialDownload::MATERIAL_TYPE_VIDEO:
                $result = $this->download_video();
                break;
            default:
                break;
        }
        if (isset($result['status']) && !$result['status']) {
            return redirect(url(strval($urlMaker)))->with(['error' => new MessageBag([
                'title' => $result['message']
            ])]);
        }
        if (!isset($result['data']) || empty($result['data'])) {
            return redirect(url(strval($urlMaker)))->with(['error' => new MessageBag([
                'title' => '数据为不存在或状态不可见'
            ])]);
        }
        if ((isset($result['data']['pics']) && empty($result['data']['pics']))
            || (isset($result['data']['videos']) && empty($result['data']['videos']))) {
            return redirect(url(strval($urlMaker)))->with(['error' => new MessageBag([
                'title' => '图片或视频数据为空'
            ])]);
        }
        $result = array_merge($result['data'], ['materialType' => intval($materialType), 'sender' => $email]);
        //新建下载任务
        $res = MaterialDownload::requestDownloadServer($result);
        if (!$res) {
            return redirect(url(strval($urlMaker)))->with(['error' => new MessageBag([
                'title' => '新建下载任务失败，请稍后重试'
            ])]);
        }
        //返回结果
        $success = new MessageBag([
            'title' => '提交工单：'.$result['name'].' 成功，下载完成后会发您邮件，请注意查收！'
        ]);
        return redirect(url(strval($urlMaker)))->with(compact('success'));
    }

    public function download_photo() {
        $objId = $this->objId;
        $sw = $this->sw;
        $imgSize = $this->imgSize ?: ImgUrl::IMAGE_SIZE_ORIGINAL;
        if (empty($objId) || !$photoDatas = dbPhotos::getPhotos($objId)) {
            return [
                'status' => false,
                'message' => "请输入正确的图片id",
            ];
        }

        $ori_photos = array();
        foreach ($photoDatas as $photoData) {
            $key = $photoData['id'];
            //获取图片用户昵称
            $user_info = Member::getUserInfoByUid($photoData['uid']);
            $save_img_name = 'name:' . $user_info['nick'] . '_remark:' . $photoData['remark'];
            $save_img_name = $this->_filterChar($save_img_name);
            $save_img_name = $this->_emojiStrConvert($save_img_name);

            // 单图还是多图
            if ($photoData['is_album'] == 1) {
                if (isset($photoData['pic_list']) && $photoData['pic_list']) {
                    $pic_list = json_decode($photoData['pic_list'], true);
                    if (is_array($pic_list) && $pic_list) {
                        foreach ($pic_list as $i => $pic) {
                            $pic_id = isset($pic['pic_org_id']) && $pic['pic_org_id'] && strlen($pic['pic_org_id']) > 22 ? $pic['pic_org_id'] : "";
                            if (empty($pic_id)) {
                                $pic_id = isset($pic['pic_id']) && $pic['pic_id'] ? $pic['pic_id'] : "";
                            }

                            if ($sw) {
                                $ori_image_src = ImgUrl::getUrlHasSWater(ImgUrl::APPTYPE_APP, $pic_id, $imgSize);
                            } else {
                                $ori_image_src = ImgUrl::getUrlNotSWater(ImgUrl::APPTYPE_APP, $pic_id, $imgSize);
                            }

                            $ori_photos[$key][$ori_image_src] = $save_img_name . "_" . ($i + 1) . $this->getImageExt($ori_image_src);
                        }
                    }
                }
            } else {
                $pic_org_id = $photoData['pic_org_id'] ?? '';
                $pic_id = $photoData['pic_id'] ?? '';
                if (empty($pic_org_id) && empty($pic_id)) {
                    return [
                        'status' => false,
                        'message' => "note生成失败",
                    ];
                }
                $picId = strlen($pic_org_id) > 22 ? $pic_org_id : $pic_id;
                if ($sw) {
                    $ori_image_src = ImgUrl::getUrlHasSWater(ImgUrl::APPTYPE_APP, $picId, $imgSize);
                } else {
                    $ori_image_src = ImgUrl::getUrlNotSWater(ImgUrl::APPTYPE_APP, $picId, $imgSize);
                }
                $ori_photos[$key][$ori_image_src] = $save_img_name . $this->getImageExt($ori_image_src);
            }
        }
        return [
            'status' => true,
            'data' => ['name' => 'photo_' . $this->uniId . '_' . $this->sw, 'pics' => $ori_photos],
        ];
    }

    //整屋案例图片下载
    public function download_article() {
        $objIds = $this->objId;
        $sw = $this->sw;
        $imgSize = $this->imgSize ?: ImgUrl::IMAGE_SIZE_ORI_NPHONE;
        if (empty($objIds)) {
            return [
                'status' => false,
                'message' => "请输入正确的整屋案例id",
            ];
        }
        $ori_photos = array();
        foreach ($objIds as $objId) {
            if(!Checker::isArticleid($objId)) {
                return [
                    'status' => false,
                    'message' => "{$objId}错误，请输入正确的整屋案例id",
                ];
            }
            $articleInfo = Article::getWholeArticle($objId);
            if (empty($articleInfo)) {
                return [
                    'status' => false,
                    'message' => "{$objId}错误，整屋案例不存在",
                ];
            }
            $key = strval($objId);
            $userInfo = Member::getUserInfoByUid($articleInfo['uid']);

            $j = 0;
            foreach ($articleInfo['show_photo_info'] as $i => $current_space) {
                //过滤掉无图片空间
                if (!isset($current_space['show_pics']) || empty($current_space['show_pics'])) {
                    continue;
                }
                foreach ($current_space['show_pics'] as $current_space_pic) {
                    if (!isset($current_space_pic['image_list']) || empty($current_space_pic['image_list'])) {
                        continue;
                    }
                    foreach ($current_space_pic['image_list'] as $value) {

                        $pic_org_id = $this->_getPicId($value['pic_url']);
                        if ($sw) {
                            $ori_image_src = ImgUrl::getUrlHasSWater(ImgUrl::APPTYPE_APP, $pic_org_id, $imgSize);
                        } else {
                            $ori_image_src = ImgUrl::getUrlNotSWater(ImgUrl::APPTYPE_APP, $pic_org_id, $imgSize);
                        }

                        $save_img_name = $current_space['name'] . '_name:' . $userInfo['nick'] . '_remark:' . $value['remark'];
                        $save_img_name = $this->_filterChar($save_img_name);
                        $save_img_name = $this->_emojiStrConvert($save_img_name);
                        $ori_photos[$key][$ori_image_src] = $save_img_name . "_" . $j . $this->getImageExt($ori_image_src);
                        $j++;
                    }
                }
            }
        }
        return [
            'status' => true,
            'data' => ['name' => 'article_' . $this->uniId . '_' . $this->sw, 'pics' => $ori_photos],
        ];
    }

    //灵感集下载
    public function download_ideabook() {
        $objId = $this->objId;
        $sw = $this->sw;
        $imgSize = $this->imgSize ?: ImgUrl::IMAGE_SIZE_ORIGINAL;
        if (empty($objId)) {
            return [
                'status' => false,
                'message' => "请输入正确的灵感集id",
            ];
        }
        $ideabookInfos = IdeaBook::getByIds($objId);
        if (empty($ideabookInfos)) {
            return [];
        }
        $ori_photos = array();
        foreach ($ideabookInfos as $ideabookInfo) {
            try {
                $key = strval($ideabookInfo['id']);
                $cover_img = [];
                if (!empty($ideabookInfo['cover_img'])) {
                    $cover_img = explode(",", $ideabookInfo['cover_img']);
                }
                $pic_info = $this->getPicsNew($ideabookInfo['id'], $ideabookInfo['uid'], $cover_img);
                if (empty($pic_info)) {
                    return [
                        'status' => false,
                        'message' => "灵感集{$key}的图片不存在，请求数据出错",
                    ];
                }
                foreach ($pic_info as $i => $photo_info) {
                    #todo 发布时候如果不是从客户端新上传而是直接从已有图片合集中上传会导致pic_org_id为空，这里暂不做报错处理，兼容一下
                    $pic_id = $photo_info['pic_org_id'] ?: $photo_info['pic_id'];
                    if ($sw) {
                        $ori_image_src = ImgUrl::getUrlHasSWater(ImgUrl::APPTYPE_APP, $pic_id, $imgSize);
                    } else {
                        $ori_image_src = ImgUrl::getUrlNotSWater(ImgUrl::APPTYPE_APP, $pic_id, $imgSize);
                    }
                    $save_img_name = 'name:' . $photo_info['nick'] . '_remark:' . $photo_info['remark'];
                    $save_img_name = $this->_filterChar($save_img_name);
                    $save_img_name = $this->_emojiStrConvert($save_img_name);
                    $ori_photos[$key][$ori_image_src] = $save_img_name . "_" . $i . $this->getImageExt($ori_image_src);
                }
            } catch (\Throwable $e) {
                var_dump($e->getMessage());
            }
        }
        return [
            'status' => true,
            'data' => ['name' => 'ideabook_' . $this->uniId . '_' . $this->sw, 'pics' => $ori_photos],
        ];
    }

    //头像下载
    public function download_user() {
        $objIds = $this->objId;
        $imgSize = $this->imgSize ?: ImgUrl::IMAGE_SIZE_ORIGINAL;
        if (empty($objIds)) {
            return [
                'status' => false,
                'message' => "请输入正确的用户id",
            ];
        }
        $ori_photos = array();
        foreach ($objIds as $objId) {
            if (!Checker::isNumericId($objId)) {
                return [
                    'status' => false,
                    'message' => "{$objId}错误，请输入正确的用户id",
                ];
            }
            $key = strval($objId);
            $picId = Member::getUserPicId($objId);
            $ori_image_src = ImgUrl::getUrl(ImgUrl::APPTYPE_PIC, $picId, $imgSize);
            $ori_photos[$key][$ori_image_src] = $objId.".jpg";
        }
        return [
            'status' => true,
            'data' => ['name' => 'user_' . $this->uniId, 'pics' => $ori_photos],
        ];
    }

    //空白模板素材下载
    public function download_blank() {
        $i = 0;
        $objId = $this->objId;
        $sw = $this->sw;
        $imgSize = $this->imgSize ?: ImgUrl::IMAGE_SIZE_ORI_NPHONE;
        $ori_photos = array();
        $blank_results = Blank::getBatchBlankByIds($objId);
        if(empty($blank_results)){
            return [
                'status' => false,
                'message' => "经验文章数据为空",
            ];
        }
        foreach ($blank_results as $blank_result) {
            $key = strval($blank_result['bid']);
            $content_arr = json_decode($blank_result['content_block'], true);
            $pic_urls = array_column($content_arr, 'pic');
            if (empty($pic_urls) && empty($blank_result['cover_pic_id'])) {
                return [
                    'status' => false,
                    'message' => "经验文章{$key}中没有图片",
                ];
            }
            $save_img_name = '经验文章';
            if (!empty($blank_result['cover_pic_id'])) {
                $ori_image_src = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $blank_result['cover_pic_id'], $imgSize);
                $ori_photos[$key][$ori_image_src] = $save_img_name . "_" . $i . $this->getImageExt($ori_image_src);
            }
            if (!empty($pic_urls)) {
                foreach ($pic_urls as $val) {
                    if (empty($val['url'])) continue;
                    $i++;
                    $pic_id = $this->_getPicId($val['url']);
                    if ($sw) {
                        $ori_image_src = ImgUrl::getUrlHasSWater(ImgUrl::APPTYPE_APP, $pic_id, $imgSize);
                    } else {
                        $ori_image_src = ImgUrl::getUrlNotSWater(ImgUrl::APPTYPE_APP, $pic_id, $imgSize);
                    }
                    $ori_photos[$key][$ori_image_src] = $save_img_name . "_" . $i . $this->getImageExt($ori_image_src);
                }
            }
        }
        return [
            'status' => true,
            'data' => ['name' => 'blank_' . $this->uniId . '_' . $this->sw, 'pics' => $ori_photos],
        ];
    }

    public function download_video()
    {
        $objId = $this->objId;
        if (empty($objId)) {
            return [
                'status' => false,
                'message' => "视频id不能为空",
            ];
        }
        $hashVideoIds = Photos::getVideoIdsByPhotoIds($objId);
        if (empty($hashVideoIds)) {
            return [];
        }
        $videoIds = array_values($hashVideoIds);

        $hashVideoInfos = Videos::getCommunityBackgroundVideosByIds($videoIds);
        if (empty($hashVideoInfos)) {
            return [];
        }

        $data = array();
        foreach ($hashVideoIds as $noteId => $videoId) {
            if (isset($hashVideoInfos[$videoId]) && $hashVideoInfos[$videoId]) {
                $hashVideoInfos[$videoId]['note_id'] = $noteId;
                $data[$noteId . ':高清播放地址'] = $hashVideoInfos[$videoId]['ori_play_url'];
                $data[$noteId . ':流畅播放地址'] = $hashVideoInfos[$videoId]['play_url'];
                $data[$noteId . ':带水印播放地址'] = $hashVideoInfos[$videoId]['water_play_url'];
            }
        }

        return [
            'status' => true,
            'data' => ['name' => 'video_' . $this->uniId, 'videos' => $data],
        ];
    }

    private function _getPicId($url)
    {
        $url_info = parse_url($url);
        $pic_id = strrchr($url_info['path'], '/');
        $pic_id = substr($pic_id, 1);
        return $pic_id;
    }

    //过滤一些特殊符号，不然下载文件文件名不对
    private function _filterChar($str){
        $str = str_replace('#','_',$str);
        $filter_char = array(' ', "\n", "\r", "&", '，', '。', '、', '.', '“', '”', ',', '|', '（', '）', '；', '！','/', '～');
        return str_replace($filter_char,'',$str);
    }

    //字符转码,主要是为了在solr存储的时候字符编码为utf8，而表情的编码不是，所以就会有错误！
    private function _emojiStrConvert($emoji_str){
        $text = '';
        if (!empty($emoji_str) && is_string($emoji_str)) {
            $text = preg_replace_callback('/[\xf0-\xf7].{3}/',
                function($r) { return '';}, $emoji_str);

            if (mb_strlen($text, 'utf-8') > 90) {
                $text = mb_substr($text, 0, 90, 'utf-8') . '...';
            }
        }
        return $text;
    }

    protected function getPicsNew($idea_book_id, $uid, $cover_img){
        $pic_arr = Ideabookcollect::getPhotos($uid, $idea_book_id);
        $photo_arr = array_unique(array_merge($cover_img , $pic_arr));
        if (empty($photo_arr)) {
            return array ();
        }
        $return = array ();
        $infos = Photos::getPhotos($photo_arr);

        if($infos && is_array($infos)) {
            foreach($infos as $id=>$info) {
                if(isset($info['pic_list']) && $info['pic_list']) {
                    $user_info = Member::getUserInfoByUid($info['uid']);
                    $info['pic_list'] = json_decode($info['pic_list'], true);
                    $i = 1;
                    foreach($info['pic_list'] as $pic) {
                        $return[] = [
                            'photo_id' => $info['id'],
                            'pic_id' => $pic['pic_id'],
                            'pic_org_id' => $pic['pic_org_id'],
                            'remark' => $i.$info['remark'],
                            'nick' => $user_info['nick']
                        ];
                        $i++;
                    }
                }
            }
        }
        return $return;
    }

    //获取图片Url后缀
    private function getImageExt($imgUrl) {
        return '.jpg';
//        return strrchr($imgUrl,'.');
    }
}
